package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.InitialFronSelector;
import com.cfets.annualAssessment.entity.Parameter;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.ParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ShenYiChou on 2017/1/16.
 */
@Controller
@RequestMapping("/admin/parameter")
public class parameterController {
    @Autowired
    private ParameterService parameterService;
    @RequestMapping("/index")
    public String index(Model model){
        return "parameter";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> parameterList(Parameter parameter){
        List<Parameter> parameterList = parameterService.getParameterPage(parameter);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(parameterList);
        tableContainer.setiTotalDisplayRecords(parameter.getTotalCount());
        tableContainer.setiTotalRecords(parameter.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid Parameter parameter, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        boolean flag = false;
        if(parameter.getId()!=null && parameter.getId()!=0){
            flag = this.parameterService.updateParameter(parameter);
        }else {
            flag = this.parameterService.newParameter(parameter);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteParameter(@PathVariable("id") int id){
        boolean flag = this.parameterService.deleteParameterById(id);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @RequestMapping(value = "/restful/initialPara",method = RequestMethod.POST)
    public ResponseEntity<?> initialParameter(){
        InitialFronSelector initialFronSelector = this.parameterService.getInitialFronSelector();
        return new ResponseEntity<>(initialFronSelector, HttpStatus.OK);
    }
}
